package com.jinke.api.modules.third.ezeeship2.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jinke.api.common.annotation.Apilog;
import com.jinke.api.common.util.CommonUtil;
import com.jinke.api.modules.app.request.CancelLabelRequest;
import com.jinke.api.modules.app.request.TrackingRequest;
import com.jinke.api.modules.third.ezeeship.model.request.EstimateRateRequest;
import com.jinke.api.modules.third.ezeeship.model.response.CreateLabelResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Component
@RequiredArgsConstructor
public class EzeeShip2Util {
    public static final String LABEL_CREATE = "https://ezeeship.com/api/ezeeship-openapi/label/create";
    public static final String LABEL_CANCEL = "https://ezeeship.com/api/ezeeship-openapi/label/cancel";
    public static final String LABEL_TRACKING = "https://ezeeship.com/api/ezeeship-openapi/label/tracking";
    public static final String ADDRESS_VALIDATE = "https://ezeeship.com/api/ezeeship-openapi/address/validate";
    public static final String GET_LABEL = "https://ezeeship.com/api/ezeeship-openapi/label/get/";
    public static Map<String, String> messages;

    private String sendPostRequest(String url, String requestBody) throws IOException {
        HttpURLConnection connection = null;
        try {

            String seq = CommonUtil.getOrderNo();

            // 创建连接
            URL apiUrl = new URL(url);
            if ("true".equals(System.getenv("local"))) {
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 10809));
                connection = (HttpURLConnection) apiUrl.openConnection(proxy);
            } else {
                connection = (HttpURLConnection) apiUrl.openConnection();
            }

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", "66406d53edac11eea67c57f8f7cd4cb3");
            connection.setDoOutput(true);

            // 写入请求体
            try (OutputStream outputStream = connection.getOutputStream()) {
                outputStream.write(requestBody.getBytes("UTF-8"));
            }

            // 获取响应
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                log.info("rec : {}, {}", seq, response.toString());
                return response.toString();
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    private String sendGetRequest(String url) throws IOException {
        HttpURLConnection connection = null;
        try {
            String seq = CommonUtil.getOrderNo();
            URL apiUrl = new URL(url);
            if ("true".equals(System.getenv("local"))) {
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 7890));
                connection = (HttpURLConnection) apiUrl.openConnection(proxy);
            } else {
                connection = (HttpURLConnection) apiUrl.openConnection();
            }

            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", "66406d53edac11eea67c57f8f7cd4cb3");

            // 获取响应
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                log.info("rec : {}, {}", seq, response.toString());
                return response.toString();
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    public void main(String[] args) {

        String resutl = getLabel("ffdbc525b5cd11eea2b5c55053509615");
        CreateLabelResponse.Data bean = JSONUtil.toBean(resutl, CreateLabelResponse.Data.class);
        System.out.println(resutl);

    }

    @Apilog(requestTypeName = "ezeeship2-预估")
    public String estimateRate(EstimateRateRequest estimateRateRequest) {

        try {
            // 发送POST请求
            String requestBody = JSONUtil.toJsonStr(estimateRateRequest);
            log.info("EzeeShip2估价接口参数------------>,{},{}", estimateRateRequest.getOrderNO(), requestBody);
            String response = sendPostRequest("https://ezeeship.com/api/ezeeship-openapi/shipment/estimateRate", requestBody);
            log.info("EzeeShip2估价接口响应参数------------>,{},{}", estimateRateRequest.getOrderNO(), response);
            // 处理响应
            return response;
        } catch (Exception e) {
            log.info("EzeeShip2估价接口异常------------>,{}", estimateRateRequest.getOrderNO());
            e.printStackTrace();
        }
        return Strings.EMPTY;
    }

    @Apilog(requestTypeName = "ezeeship2-下单")
    public String createLabel(EstimateRateRequest request) {
        String orderNO = request.getOrderNO();
        try {
            EstimateRateRequest tmp = new EstimateRateRequest();
            BeanUtil.copyProperties(request, tmp);
            tmp.setOrderNO(tmp.getPlatformNo());
            String param = JSONUtil.toJsonStr(tmp);
            log.info("------------EzeeShip2 下单参数------------->,{},{}", orderNO, param);
            // 发送POST请求
            String response = sendPostRequest(LABEL_CREATE, param);
            log.info("------------EzeeShip2 下单响应------------->,{},{}", orderNO, response);
            // 处理响应
            return response;
        } catch (Exception e) {
            log.info("------------EzeeShip2 下单异常------------->,{}", orderNO);
            e.printStackTrace();
        }
        return Strings.EMPTY;
    }

    /**
     * 取消
     * @param objectId
     * @param orderNo
     * @return
     */
    @Apilog(requestTypeName = "EzeeShip2-取消")
    public String cancelLabel(String objectId, String orderNo) {
        try {
            // 发送POST请求
            CancelLabelRequest cancelLabelRequest = new CancelLabelRequest();
            cancelLabelRequest.setObjectId(objectId);
            String param = JSONUtil.toJsonStr(cancelLabelRequest);
            log.info("-------------EzeeShip2 取消参数------------->,{},{}", orderNo, param);
            String response = sendPostRequest(LABEL_CANCEL, param);
            log.info("-------------EzeeShip2 取消响应------------->,{},{}", orderNo, param);

            return response;
        } catch (Exception e) {
            log.info("-------------EzeeShip2 取消异常------------->,{},{}", orderNo, e.getMessage());

        }
        return Strings.EMPTY;
    }

    public String tracking(String trackingNumber) {

        try {
            // 发送POST请求
            TrackingRequest cancelLabelRequest = new TrackingRequest();
            cancelLabelRequest.setTrackingNumber(trackingNumber);
            String requestBody = JSONUtil.toJsonStr(cancelLabelRequest);
            log.info("-------------EzeeShip2 跟踪请求------------->,{},{}", trackingNumber, requestBody);
            String response = sendPostRequest(LABEL_TRACKING, requestBody);
            log.info("-------------EzeeShip2 跟踪响应------------->,{},{}", trackingNumber, response);
            // 处理响应
            return response;
        } catch (Exception e) {
            log.info("-------------EzeeShip2 跟踪异常------------->,{},{}", trackingNumber, e.getMessage());
        }
        return Strings.EMPTY;
    }

    public String validateAddress(EstimateRateRequest.Address address) {
        String requestBody = null;
        try {
            // 发送POST请求
            requestBody = JSONUtil.toJsonStr(address);
            log.info("-------------EzeeShip2 校验地址请求------------->,{}", requestBody);

            String response = sendPostRequest(ADDRESS_VALIDATE, requestBody);
            log.info("-------------EzeeShip2 校验地址响应------------->,{}", response);
            return response;
        } catch (Exception e) {
            log.info("-------------EzeeShip2 校验地址异常------------->,{},{}", requestBody, e.getMessage());
        }
        return Strings.EMPTY;
    }

    public String getLabel(String objectId) {

        try {
            log.info("-------------EzeeShip2获取面单请求------------->,{}", objectId);

            String response = sendGetRequest(GET_LABEL + objectId);
            log.info("-------------EzeeShip2获取面单响应------------->,{}", response);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Strings.EMPTY;
    }


    public String fmtMsg(String msg) {
        if (StringUtils.isNotBlank(msg)) {
            for (String key : messages.keySet()) {
                if (msg.contains(key)) {
                    msg = messages.get(key);
                    break;
                }
            }
        }
        return msg;
    }

}
